package com.eras.shoes.ui;

import android.Manifest;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;

import com.eras.shoes.R;
import com.eras.shoes.contents.BleBean;
import com.eras.shoes.contents.MessageEvent;
import com.eras.shoes.utils.BluetoothController;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;
import java.util.Objects;


public class BlueActivity extends Activity {
    private static final int PERMISSION_REQUEST_CODE = 1;
    private BtTemperatureReceiver broadcastReceiver;
    private TextView tvMainBoardBack;
    private TextView tvMainRefresh;
    private RecyclerView rvMainBoardBt;
    private HashMap<String, String> bleMap = new HashMap<>();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_main_board);
        initView();


    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    private void initView() {
        tvMainBoardBack = findViewById(R.id.tv_main_board_back);//返回
        tvMainRefresh = findViewById(R.id.tv_main_refresh);//蓝牙刷新
        rvMainBoardBt = findViewById(R.id.rv_main_board_bt);//蓝牙搜索列表
        findViewById(R.id.btn_scan_code);//扫描二维码按钮
//        findViewById(R.id.tv_serial_number);//扫描返回的序列号
        findViewById(R.id.tv_putin_comparison_result);//入库比对结果
        findViewById(R.id.btn_write);//将序列号写入主板
        findViewById(R.id.tv_write_result);//写入结果
        findViewById(R.id.btn_save);//保存到后台服务器
        findViewById(R.id.tv_save_result);//保存结果




    }

    @Override
    protected void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
        requestPermissions();
        refreshBle();
    }

    /**
     * 检测是否获取定位权限
     */
    private void requestPermissions() {
        // 检查权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {

//            ToastUtils.show(getBaseContext(), "未获取定位权限");
            // 权限未被授予，请求权限
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                    PERMISSION_REQUEST_CODE);
        } else {
            // 权限已被授予，可以进行相关操作
            // ...
            new Thread(() -> initBtState()).start();
        }
    }
    /**
     * 初始化蓝牙状态广播监听
     */
    private void initBtState(){
        if (BluetoothController.getInstance().isBleOpen()) {
            BluetoothController.getInstance().startScanBle();
        } else {
            BluetoothController.getInstance().initBle(this);
        }
        broadcastReceiver = new BtTemperatureReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
        registerReceiver(broadcastReceiver,intentFilter);
//        BluetoothController.getInstance().startScanBle();
    }
    private void refreshBle() {
        BluetoothController.getInstance().stopScanBle();
//        bleDevAdapter.clear();
//        bleMap.clear();
        BluetoothController.getInstance().startScanBle();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            case PERMISSION_REQUEST_CODE: {
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 权限被授予，可以进行相关操作
                    // ...
//                    ToastUtils.show(ConnectDeviceActivity.this, "定位权限申请成功");
//                    Toast.makeText(this, "定位权限申请成功", Toast.LENGTH_SHORT).show();
                    new Thread(() -> initBtState()).start();

                } else {
                    // 权限被拒绝，需要进行一些提示或者引导用户去设置页面开启权限
//                    ToastUtils.show(ConnectDeviceActivity.this, "申请位置权限被拒绝，请去设置中开启");
//                    Toast.makeText(this, "需要位置权限", Toast.LENGTH_SHORT).show();
                }
                return;
            }
            default:
                throw new IllegalStateException("Unexpected value: " + requestCode);
        }
    }

    /**
     * 蓝牙状态广播回调
     */
    class BtTemperatureReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            //注意!这里是先拿action 等于 BluetoothAdapter.ACTION_STATE_CHANGED 在解析intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, 0)
            if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(Objects.requireNonNull(action))) {
                int blState = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, 0);
                switch (blState) {
                    case BluetoothAdapter.STATE_TURNING_ON:
//                        setPoint(false);
//                        ToastUtils.show(ConnectDeviceActivity.this, "蓝牙正在开启中……");
//                        Toast.makeText(ConnectDeviceActivity.this,"蓝牙正在开启中……，请稍等",Toast.LENGTH_SHORT).show();
                        break;
                    case BluetoothAdapter.STATE_ON:
//                        setPoint(true);
//                        ToastUtils.show(ConnectDeviceActivity.this, "蓝牙开启成功");
//                        Toast.makeText(ConnectDeviceActivity.this,"蓝牙开启成功",Toast.LENGTH_SHORT).show();
//                        BluetoothController.getInstance().startScanBle();
                        break;
                    case BluetoothAdapter.STATE_TURNING_OFF:
//                        ToastUtils.show(ConnectDeviceActivity.this, "蓝牙正在关闭中……，请稍等");
//                        Toast.makeText(ConnectDeviceActivity.this,"蓝牙正在关闭中……，请稍等",Toast.LENGTH_SHORT).show();
//                        setPoint(false);
                        break;
                    case BluetoothAdapter.STATE_OFF:
//                        ToastUtils.show(ConnectDeviceActivity.this, "蓝牙已关闭");
//                        Toast.makeText(ConnectDeviceActivity.this,"蓝牙已关闭",Toast.LENGTH_SHORT).show();
//                        setPoint(false);
                        new Thread(() -> initBtState()).start();
                        break;
                    case BluetoothAdapter.ERROR:
//                        setPoint(false);
                        new Thread(() -> initBtState()).start();
                        break;
                    default:
                        break;
                }
            }

        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(@NonNull MessageEvent event) {
        BleBean bleBean;
        switch (event.getAction()) {
            case MessageEvent.BLE_SCAN_RESULT:
                bleBean = (BleBean) event.getData();
                String name = bleBean.getName();
                String address = bleBean.getAddress();
                int rssi = bleBean.getRssi();

                break;
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
